package com.base.bean;

import java.io.Serializable;

import javax.faces.bean.RequestScoped;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;

@Controller
@RequestScoped
public class LoginBean implements Serializable {
	
	private static final long serialVersionUID = 8588731142005518963L;
	
	private static final Logger LOGGER = LoggerFactory.getLogger(LoginBean.class);
	
	private String usuario;
	private String password;
	
	@Autowired
	private AuthenticationManager authenticationManager = null;

	public String login() {
		
		
		
		try {
            Authentication request = new UsernamePasswordAuthenticationToken(this.getUsuario(), this.getPassword());
            Authentication result = authenticationManager.authenticate(request);
            SecurityContextHolder.getContext().setAuthentication(result);
        
            if (result.isAuthenticated()) {
    			return "index";
    		}
            
		} catch (AuthenticationException e) {
			LOGGER.info("Login fallido, Usuario: "+this.getUsuario());
        }
		
		return "login";
	}

	public String getUsuario() {
		return usuario;
	}

	public void setUsuario(String usuario) {
		this.usuario = usuario;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public AuthenticationManager getAuthenticationManager() {
		return authenticationManager;
	}

	public void setAuthenticationManager(AuthenticationManager authenticationManager) {
		this.authenticationManager = authenticationManager;
	}
	
}